package com.ww.springboot.boot.thread.study.base.lock.aqs.demo.lock1;

import com.ww.springboot.boot.thread.study.base.lock.aqs.paint.PaintAqs;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * 简单锁 每次只让一个线程获取锁 此方法没有判断获取锁的线程是哪个  随便一个地方调用解锁方法都能解锁 --隐患很大
 *
 * @author wanwei
 * @since 2023-03-16 22:07
 */
public class MySimpleLock implements Lock {

    private MySync mySync = new MySync();

    public MySimpleLock() {
        PaintAqs.main(this.mySync);
    }

    @Override
    public void lock() {
        mySync.acquire(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        mySync.acquireInterruptibly(1);
    }

    @Override
    public boolean tryLock() {
        return mySync.tryAcquire(1);
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return mySync.tryAcquireNanos(1, unit.toNanos(time));
    }

    @Override
    public void unlock() {
        mySync.release(1);
    }

    @Override
    public Condition newCondition() {
        return mySync.conditionObject();
    }
}
